package com.studentSystem.controller;

import com.studentSystem.pojo.Grades;
import com.studentSystem.service.GradesService;
import com.studentSystem.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

@RestController
@RequestMapping("/grades")
@Validated
public class GradesController {
    @Autowired
    private GradesService gradesService;

    @GetMapping("/student")
    public ResultUtil<List<Grades>> getStudentGrades(@RequestParam Long studentId) {
        return ResultUtil.success(gradesService.getGradesByStudentId(studentId));
    }

    @GetMapping("/average")
    public ResultUtil getStudentAverageGrade(@RequestParam Long studentId) {
        double averageGradeByStudentId = gradesService.getAverageGradeByStudentId(studentId);
        DecimalFormat df = new DecimalFormat("#.00");
        String averageGradeByStudentIdString = df.format(averageGradeByStudentId);
        return ResultUtil.success(averageGradeByStudentIdString);
    }

    @GetMapping("/total")
    public ResultUtil getStudentTotalGrade(@RequestParam Long studentId) {
        BigDecimal totalGradeByStudentId = gradesService.getTotalGradeByStudentId(studentId);
        return ResultUtil.success(totalGradeByStudentId);
    }

    @GetMapping("/all")
    public ResultUtil<List<Grades>> getStudentGradesAll() {
        return ResultUtil.success(gradesService.getGradesByStudentIdAll());
    }

    @PostMapping("/add")
    public ResultUtil addStudentGrade(@RequestBody Grades grades){
        if (grades.getCourseId()==null||grades.getStudentId()==null||grades.getGrade()==null) return ResultUtil.error("输入有误！");
        Grades grade = gradesService.exiting(grades.getStudentId(), grades.getCourseId());
        if(grade!=null) return ResultUtil.error("该成绩已存在！");
        gradesService.addGrade(grades);
        return ResultUtil.success();
    }

    @PostMapping("/update")
    public ResultUtil updateStudentGrade(@RequestBody Grades grades){
        if (grades.getCourseId()==null||grades.getStudentId()==null||grades.getGrade()==null) return ResultUtil.error("输入有误！");
        gradesService.updateGrade(grades);
        return ResultUtil.success();
    }

    @DeleteMapping("/delete")
    public ResultUtil deleteStudentGrrade(Long studentId, Long courseId){
        if (studentId==null||courseId==null) return ResultUtil.error("输入有误！");
        gradesService.delete(studentId, courseId);
        return ResultUtil.success();
    }
}
